<template>
  <Form ref="loginForm" :model="form" :rules="rules" @keydown.enter.native="handleSubmit">
    <FormItem prop="userName">
      <Input v-model="form.userName" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="ios-person"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="form.password" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="md-lock"></Icon>
        </span>
      </Input>
    </FormItem>
    <FormItem prop="yanzhengma" >
      <div style="display: inline;">
        <img style="margin-left: 5px;margin-top: 1px;height: 32px;width: 90px" class="login-yanzhengma" :src="yzm_message" v-on:click="change_yzm_message">
        <Input style="width: 170px;float: left" v-model="form.yanzhengma" placeholder="请输入图形验证码">
        <span slot="prepend">
          <Icon :size="14" type="ios-key"></Icon>
          </span>
        </Input>
      </div>
    </FormItem>
    <FormItem>
      <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
  </Form>
</template>
<script>
  import {baseUrl} from '@/libs/baseUrl'
export default {
  name: 'LoginForm',
  props: {
    userNameRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ]
      }
    },
    passwordRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ]
      }
    },
    yanzhengmaRules: {
      type: Array,
      default: () => {
        return [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  data () {
    return {
      form: {
        userName: 'admin',
        password: '',
        yanzhengma:'',
      },
      yzm_message: baseUrl + '/draw/'+this.yzm()
    }
  },
  computed: {
    rules () {
      return {
        userName: this.userNameRules,
        password: this.passwordRules,
        yanzhengma: this.yanzhengmaRules
      }
    }
  },
  methods: {
    handleSubmit () {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$emit('on-success-valid', {
            userName: this.form.userName,
            password: this.form.password
          })
        }
      })
    },
    yzm(){
      let charactors="ab1cd2ef3gh4ij5kl6mn7opq8rst9uvw0xyz";
      let value='',i;
      for(let j=1;j<=4;j++){
        i = parseInt(35*Math.random());
        value = value + charactors.charAt(i);
      }
      return value
    },
    change_yzm_message: function () {
      // `this` 在方法里指向当前 Vue 实例，这个需要加一个岁数变化，直接更新到请求，如果不加随机数默认使用缓存
      this.yzm_message = baseUrl + '/draw/'+ this.yzm();
    },
  }
}
</script>
